const ora = require('ora');
const chalk = require('chalk');
const webpack = require('webpack');
const util = require('./util');
const config = require('./../config.js');

const { PRODUCT_CONFIG, NODE_ENV } = process.env;
let webpackConfig = {};
webpackConfig = require('./webpack.config.js');

if (!config.entry || config.entry.length === 0) {
  console.log(chalk.red('请先配置config.json里的entry入口插件目录'));
  process.exit();
}
let initBbuild = false;
util.addSupportH5Config().then(() => {
  const spinner = ora('开始构建项目...');
  spinner.start();
  webpack(webpackConfig, (err, stats) => {
    spinner.stop();
    if (!initBbuild) {
      process.stdout.write(
        `${stats.toString({
          assets: true,
          colors: true,
          modules: false,
          children: false,
          chunks: false,
          chunkModules: false,
          warnings: false,
        })}\n\n`
      );
      // util.buildViews(webpackConfig.entry);
      initBbuild = true;
      if (!stats.hasErrors()) {
        console.log(chalk.cyan('  构建成功！\n'));
        PRODUCT_CONFIG != 'je' && util.zip();

        if (NODE_ENV === 'development' && PRODUCT_CONFIG !== 'je') {
          require('../server/dev');
        }
      }
    } else {
      // 只输出修改的文件
      const { assets } = stats.compilation;
      for (const key in assets) {
        const file = assets[key];
        const module = key.split('/')[0];
        if (file.emitted) {
          console.log(chalk.cyan(`[${module}]：`), chalk.green(key));
        }
      }
      console.log(chalk.gray(new Date(stats.endTime).toString()), '\n');
    }
    PRODUCT_CONFIG != 'je' && util.copyComment();
  });
});
